package com.kele.modbus;

import com.kele.message.response.ResponseFrameFactory;
import com.kele.message.base.ResponseFrame;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * modbus 消息解析器
 */
public class ModbusMessageDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        ResponseFrame responseFrame = decode(ctx, in);
        if (responseFrame != null){
            System.out.println(responseFrame);
            out.add(responseFrame);
        }
    }

    private ResponseFrame decode(ChannelHandlerContext ctx, ByteBuf in) {
        short addressCode = in.readUnsignedByte();
        short functionCode = in.readUnsignedByte();
        ResponseFrame responseFrame = null;
        try {
            responseFrame = ResponseFrameFactory.createMessage(functionCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (responseFrame != null){
            responseFrame.decode(in.readBytes(in.readableBytes()), addressCode, functionCode);
        }
        return responseFrame;
    }
}
